package com.laputa.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.EventDispatchAction;

import com.laputa.service.method.FriendListService;
import com.laputa.service.model.MainFrameData;

public class FriendListAction extends EventDispatchAction {
	FriendListService friendListService;
	
	public void setFriendListService(FriendListService friendListService) {
		this.friendListService = friendListService; 
	}
	
	public ActionForward showList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String userID = ((MainFrameData) request.getSession().getAttribute("userData")).getId().toString();
		request.setAttribute("friendListData", friendListService.getFriendList(userID));
		return mapping.findForward("showList");
	}
	
	public ActionForward showSingle(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response) {
		DynaActionForm daForm = (DynaActionForm) form;
		String friendID = (String) daForm.get("userID");
		request.setAttribute("userID", friendID);
		
		System.out.println("from friendlistaction, the user in session is " + ((MainFrameData) request.getSession().getAttribute("userData")).getName());
		MainFrameData friendData = friendListService.loadFriendFrame(friendID);
		System.out.println("from friendlistaction, the user in session is " + ((MainFrameData) request.getSession().getAttribute("userData")).getName());
		request.setAttribute("friendData", friendData);
		System.out.println("from friendlistaction, the user in session is " + ((MainFrameData) request.getSession().getAttribute("userData")).getName());
		
		return mapping.findForward("showSingle");
	}

	public ActionForward addFriend(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		DynaActionForm daForm = (DynaActionForm) form;
		String userID = ((MainFrameData) request.getSession().getAttribute("userData")).getId().toString();
		String friendName = (String) daForm.get("friendName");
		
		friendListService.addFriendByName(userID, friendName);
		
		request.setAttribute("friendListData", friendListService.getFriendList(userID));
		
		return mapping.findForward("showList");
	}
}
